import type {ProColumns} from '@ant-design/pro-table';
import {crud} from './api';
import BasicForm, {
  ENV_STACK_MAPPING,
  INGRESS_STACK_MAPPING,
  PORT_STACK_MAPPING,
  VOLUME_STACK_MAPPING,
} from './form';
import BasicFormTable from '@/components/BasicFormTable';
import {formatMappingFromListToStr, formatMappingFromStrToList} from '@/utils/utils';

const INGRESS_STACK_KEYS = INGRESS_STACK_MAPPING.map((item) => item.name);
const PORT_STACK_KEYS = PORT_STACK_MAPPING.map((item) => item.name);
const VOLUME_STACK_KEYS = VOLUME_STACK_MAPPING.map((item) => item.name);
const ENV_STACK_KEYS = ENV_STACK_MAPPING.map((item) => item.name);
const SEPARATORS = [';', ':'];

export default () => {
  const normalize = (data: AnyFields) => {
    data['ingress_config'] = formatMappingFromListToStr(INGRESS_STACK_KEYS, SEPARATORS, data.ingress);
    data['port_config'] = formatMappingFromListToStr(PORT_STACK_KEYS, SEPARATORS, data.ports);
    data['volume_config'] = formatMappingFromListToStr(VOLUME_STACK_KEYS, SEPARATORS, data.volumes);
    data['env_config'] = formatMappingFromListToStr(ENV_STACK_KEYS, SEPARATORS, data.envs);
    return data;
  };

  const columns: ProColumns<StackEntity>[] = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '镜像名称',
      dataIndex: 'image',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      key: 'created',
      dataIndex: 'created',
      valueType: 'dateTime',
      hideInSearch: true,
    },
  ];

  return (
    <BasicFormTable<StackEntity>
      title={'组件'}
      columns={columns}
      postData={(data) =>
        data.map((item) => ({
          ...item,
          ingress: formatMappingFromStrToList(INGRESS_STACK_KEYS, SEPARATORS, item.ingress_config),
          ports: formatMappingFromStrToList(PORT_STACK_KEYS, SEPARATORS, item.port_config),
          volumes: formatMappingFromStrToList(VOLUME_STACK_KEYS, SEPARATORS, item.volume_config),
          envs: formatMappingFromStrToList(ENV_STACK_KEYS, SEPARATORS, item.env_config),
        }))
      }
      crud={{
        ...crud,
        add: (data) => crud.add(normalize(data)),
        update: (data) => crud.update(normalize(data)),
      }}
      addForm={<BasicForm/>}
      updateForm={<BasicForm/>}
    />
  );
};
